package com.tul.exercise.base.string.format;

import java.util.Formatter;

/**
 * @Description 《java编程思想》第13章 示例8：
 * <p>
 * string复杂的格式化输出
 **/
public class Receipt {
    private double total = 0;
    private Formatter f = new Formatter(System.out);

    // 控制宽度
    private int width;

    // title 的格式控制字符串
    private String titlePattern;

    // price 的格式控制字符串
    private String pricePattern;

    public void setTitlePattern(int width1, int width2, int width3) {
        this.titlePattern = "%-" + width1 + "s " + "%" + width2 + "s " + "%" + width3 + "s\n";
    }

    public String getTitlePattern() {
        return this.titlePattern;
    }

    public void setPricePattern(int width1, int width2, int width3, int width4) {
        this.pricePattern = "%-" + width1 + "." + width1 + "s " + " %" + width2 + "d " + " %" + width3 + "." + width4 + "f\n";
    }

    public String getPricePattern() {
        return this.pricePattern;
    }


    public void printTitle() {
        f.format(getTitlePattern(), "Item", "Qty", "Price");
        f.format(getTitlePattern(), "----", "----", "----");
    }

    public void print(String name, int qty, double price) {
        f.format(getPricePattern(), name, qty, price);
        total += price;
    }

    public void printTotal() {
        f.format("%-15s %5s %10.2f\n", "Tax", "", total * 0.06);
        f.format("%-15s %5s %10s\n", "", "", "----");
        f.format("%-15s %5s %10.2f\n", "Total", "", total * 1.06);
    }

    public static void main(String[] args) {


        Receipt receipt = new Receipt();
        receipt.setTitlePattern(20, 10, 15);
        receipt.setPricePattern(20, 10, 15, 4);

        receipt.printTitle();
        receipt.print("Jack's Magic Beans", 4, 4.52);
        receipt.print("Princess Peas", 3, 5.1);
        receipt.print("Three Bear Porridge", 1, 14.29);
        receipt.printTotal();
    }
}
